class VotesController < ApplicationController
  # GET /votes
  # GET /votes.json
  def index
    @votes = Vote.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @votes }
    end
  end

  # GET /votes/1
  # GET /votes/1.json
  def show
    @vote = Vote.find(params[:id])


    respond_to do |format|
      format.html # show.html.erb
      format.json { 
        @vote = Vote.find_by_sql("select 
          votes.id,votes.title,votes.subtitle,
          sections.title,sections.subtitle,sections.instruction,
          control_groups.name,control_groups.max,control_groups.min,
          candidates.name
          from target_question_boxes 
          left join control_groups on control_groups.id = control_group_id 
          left join sections on sections.id = control_groups.section_id
          left join votes on votes.id = sections.vote_id
          left join candidates on candidates.id = target_question_boxes.candidate_id
          left join questions on questions.id = target_question_boxes.question_id
          left join orgs on orgs.id = target_question_boxes.org_id
          where votes.isopen = 'true'
          ") 
        render json: @vote 
      }
    end
  end

  # GET /votes/new
  # GET /votes/new.json
  def new
    @vote = Vote.new
    1.times do  
      section = @vote.sections.build
      2.times { 
        control_group = section.control_groups.build
        3.times{control_group.target_question_boxes.build}  
      }  
    end  


    @candidates = Candidate.includes(:org).order("org_id asc")
    @questions = Question.all
    @orgs = Org.all
    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @vote }
    end
  end

  # GET /votes/1/edit
  def edit
    @vote = Vote.find(params[:id])
  end

  # POST /votes
  # POST /votes.json
  def create
    @vote = Vote.new(params[:vote])

    respond_to do |format|
      if @vote.save
        format.html { redirect_to @vote, notice: 'Vote was successfully created.' }
        format.json { render json: @vote, status: :created, location: @vote }
      else
        format.html { render action: "new" }
        format.json { render json: @vote.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /votes/1
  # PUT /votes/1.json
  def update
    @vote = Vote.find(params[:id])

    respond_to do |format|
      if @vote.update_attributes(params[:vote])
        format.html { redirect_to @vote, notice: 'Vote was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @vote.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /votes/1
  # DELETE /votes/1.json
  def destroy
    @vote = Vote.find(params[:id])
    @vote.destroy

    respond_to do |format|
      format.html { redirect_to votes_url }
      format.json { head :no_content }
    end
  end
end
